<template>
  <div class="user-dropdown" ref="dropdownRef" v-click-outside="closeDropdown">
    <!-- 下拉触发区：头像 + 用户名 + 红点 + 自定义箭头 -->
    <el-dropdown
      :visible="isDropdownVisible"
      @visible-change="handleVisibleChange"
      trigger="click"
    >
      <span class="dropdown-trigger">
        <el-avatar :src="userAvatar" class="avatar" />
        <span class="username">{{ username }}</span>
        <!-- 用户名右上角红点：有未读消息时显示 -->
        <el-badge v-if="unReadCount > 0" is-dot class="unread-dot" />

        <!-- 自定义箭头图标 -->
        <span class="custom-arrow" :class="{ rotate: isDropdownVisible }">
          <svg
            width="14"
            height="8"
            viewBox="0 0 14 8"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M1 1L7 7L13 1"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            />
          </svg>
        </span>
      </span>

      <!-- 下拉菜单内容 -->
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item>
            <!-- 公告项红点：显示具体条数 -->
            <el-badge :value="noticeCount" class="notice-badge" />
            公告
          </el-dropdown-item>
          <el-dropdown-item>预测推送</el-dropdown-item>
          <el-dropdown-item>个人信息</el-dropdown-item>
          <el-dropdown-item>退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ClickOutside as vClickOutside } from "element-plus";
import {
  ElBadge,
  ElAvatar,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
} from "element-plus";

// 模拟用户数据与未读消息
const username = ref("用户名");
const userAvatar = ref("https://picsum.photos/id/64/200/200"); // 使用示例头像
const unReadCount = ref(1); // 用户名右上角红点：有未读消息时>0
const noticeCount = ref(7); // 公告项具体条数

// 下拉菜单展开状态
const isDropdownVisible = ref(false);
const dropdownRef = ref(null);

// 点击外部区域时关闭下拉菜单
const closeDropdown = () => {
  isDropdownVisible.value = false;
};

// 监听下拉菜单展开/折叠事件
const handleVisibleChange = (visible) => {
  isDropdownVisible.value = visible;
};
</script>

<style scoped>
.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  position: relative;
  padding: 8px;
}

.dropdown-trigger {
  display: flex;
  align-items: center;
  position: relative;
}

.avatar {
  width: 32px;
  height: 32px;
  margin-right: 8px;
}

.username {
  margin-right: 4px;
  font-size: 14px;
}

.unread-dot {
  position: absolute;
  top: -2px;
  right: -6px;
}

/* 自定义箭头样式 */
.custom-arrow {
  margin-left: 6px;
  transition: transform 0.2s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 展开时箭头旋转 */
.custom-arrow.rotate {
  transform: rotate(180deg);
}

.notice-badge {
  margin-right: 6px;
}

/* 为下拉菜单添加过渡动画 */
.el-dropdown-menu {
  transition: all 0.2s ease-in-out;
}
</style>
